﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace UploadBlobToAzure
{
    public partial class UploadBlob : Form
    {
        string folderLocation=string.Empty;
        string folderName=string.Empty;
        string fileName=string.Empty;
        public List<string> blobList = new List<string>();
        string cmdToBeExecuted=string.Empty;
        string blobEndPoint=string.Empty;
        string accountKey=string.Empty;
        string[] linesDestLog={string.Empty};
        string totalFilesTransfered = string.Empty;
        string filesTranferedSuccessfully = string.Empty;
        string filesFailed = string.Empty; 
        
        public UploadBlob()
        {
            InitializeComponent();
            radYes.Checked = true;
            radNo.Checked = false;

            cmbFileSelection.Enabled = false;
            radCreateDir.Enabled = false;
            radNotCreateDir.Enabled = false;
            lblCreareNewDirectoryonBlob.Enabled = false;
            lblDirectoryName.Enabled = false;
            txtDirName.Enabled = false;
            lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
        }

        public void setBlobList(List<string> m_blobList)
        {
            blobList.AddRange(m_blobList);
            cmbBlobDir.DataSource = blobList;
        }
        public void setBlobEndPoint(string m_blobEndPoint)
        {
            blobEndPoint = m_blobEndPoint;
        }

        public void setaccountKey(string m_accountKey)
        {
           accountKey = m_accountKey;
        }

        private void btnBrowseFileSystem_Click(object sender, EventArgs e)
        {
            if (browseFolder.ShowDialog() == DialogResult.OK)
            {
                folderLocation = browseFolder.SelectedPath.Trim();
                folderName = Path.GetFileName(folderLocation);
            }
            else
            {

                folderName = string.Empty;
                folderLocation = string.Empty;
               
            }             
            if (folderLocation != "")
            {
                lblFolderLocation.Text = "The Folder Selected is :" + folderLocation;
                string[] fileList = Directory.GetFiles(folderLocation);
                cmbFileSelection.DataSource = fileList;
            }
            else
            {
                lblFolderLocation.Text = "There is no folder selected, please select a folder before proceeding";
            }
        }



        private void radYes_Click(object sender, EventArgs e)
        {
            cmbFileSelection.Enabled = false;
            radCreateDir.Enabled = false;
            radNotCreateDir.Enabled = false;
            lblCreareNewDirectoryonBlob.Enabled = false;
            lblDirectoryName.Enabled = false;
            txtDirName.Enabled = false;
        }


       
        private void radNo_Click(object sender, EventArgs e)
        {
            if (lblFolderLocation.Text == "There is no folder selected, please select a folder before proceeding")
            {
                MessageBox.Show("Please select a folder first by clicking on the browse button!!");
                radNo.Checked = false;
                radYes.Checked = true;
            }
            else
            {
                cmbFileSelection.Enabled = true;
                radCreateDir.Enabled = true;
                radNotCreateDir.Enabled = true;
                radNotCreateDir.Checked = true;
                lblCreareNewDirectoryonBlob.Enabled = true;
            }
        }


        private void radCreateDir_Click(object sender, EventArgs e)
        {
            lblDirectoryName.Enabled = true;
            txtDirName.Enabled = true;
        }


        private void radNotCreateDir_Click(object sender, EventArgs e)
        {
            lblDirectoryName.Enabled = false;
            txtDirName.Enabled = false;
        }

        

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if(File.Exists("dest.log"))
            {
                File.Delete("dest.log");
            }

            if (radYes.Checked)
            {                
                try
                {
                    if (cmbBlobDir.SelectedItem.ToString() == string.Empty)
                    {
                        MessageBox.Show("Please select a location on Azure where the file will be uploaded from the dropdown");
                        this.DialogResult = DialogResult.None;
                    }
                    else if (folderLocation==string.Empty)
                    {
                        MessageBox.Show("Please select a Folder on the local file system by clicking on browse button");
                        this.DialogResult = DialogResult.None;
                    }
                    else
                    {
                        Process cmd = new Process();
                        ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                        azcopyProcessStartInfo.FileName = "CMD.exe";
                        string cmdToBeExecuted = " azcopy.exe" + "  \"" + folderLocation + "\"  " + " \"" + blobEndPoint + cmbBlobDir.SelectedItem.ToString().Substring(1) + folderName + "\" " + " /destKey:" + accountKey + "   /v  /Y  >dest.log";
                        azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                        azcopyProcessStartInfo.UseShellExecute = false;
                        azcopyProcessStartInfo.CreateNoWindow = true;
                        azcopyProcessStartInfo.RedirectStandardError = true;
                        cmd.StartInfo = azcopyProcessStartInfo;                        
                        cmd.Start();
                        if(!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                        {
                            MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                        }
                        cmd.WaitForExit();

                        /*validation section*/

                        int output = validateCompletedRequest();
                        if (output == 0)
                        {
                            this.DialogResult = DialogResult.None;
                        }
                        else if (output == 1)
                        {
                            this.Close();
                        }
                        else if (output == 2)
                        {
                            this.DialogResult = DialogResult.Cancel;
                            this.Close();
                        }    
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.DialogResult = DialogResult.None;
                }
                            
            }
            else if(radNo.Checked)
            {
                if (radNotCreateDir.Checked)
                {
                    try
                    {
                        if (cmbBlobDir.SelectedItem.ToString() == string.Empty)
                        {
                            MessageBox.Show("Please select a location on Azure where the file will be uploaded from the dropdown");
                            this.DialogResult = DialogResult.None;
                        }
                        else if (folderLocation==string.Empty)
                        {
                                MessageBox.Show("Please select a Folder on the local file system by clicking on browse button");
                                this.DialogResult = DialogResult.None;
                         }       
                        else if (cmbFileSelection.SelectedItem.ToString() == string.Empty)
                        {
                            MessageBox.Show("Please select a File to be Uploaded to Azure");
                            this.DialogResult = DialogResult.None;
                        }
                        else
                        {
                            Process cmd = new Process();
                            ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                            azcopyProcessStartInfo.FileName = "CMD.exe";
                            string cmdToBeExecuted = " azcopy.exe" + "  \"" + folderLocation + "\"  " + " \"" + blobEndPoint + cmbBlobDir.SelectedItem.ToString().Substring(1) + "\"  " + cmbFileSelection.SelectedItem.ToString() + " /destKey:" + accountKey + "   /v  /Y  >dest.log";
                            azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                            azcopyProcessStartInfo.UseShellExecute = false;
                            azcopyProcessStartInfo.CreateNoWindow = true;
                            azcopyProcessStartInfo.RedirectStandardError = true;
                            cmd.StartInfo = azcopyProcessStartInfo;
                            cmd.Start();
                            if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                            {
                                MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                            }
                            cmd.WaitForExit();
                            /*validation section*/

                            int output = validateCompletedRequest();
                            if (output == 0)
                            {
                                this.DialogResult = DialogResult.None;
                            }
                            else if (output == 1)
                            {
                                this.Close();
                            }
                            else if (output == 2)
                            {
                                this.DialogResult = DialogResult.Cancel;
                                this.Close();
                            }      
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        this.DialogResult = DialogResult.None;
                    }
                }
                else if(radCreateDir.Checked)
                {
                    try
                    {
                        if (cmbBlobDir.SelectedItem.ToString() == "")
                        {
                            MessageBox.Show("Please select a location on Azure where the file will be uploaded from the dropdown");
                        }
                        if (cmbFileSelection.SelectedItem.ToString() == "")
                        {
                            MessageBox.Show("Please select a File to be Uploaded to Azure");
                        }
                        if (!IsAlphaNum(txtDirName.Text))
                        {
                            MessageBox.Show("Please give a valid name for the Directory");
                        }
                        else
                        {
                            Process cmd = new Process();
                            ProcessStartInfo azcopyProcessStartInfo = new ProcessStartInfo();
                            azcopyProcessStartInfo.FileName = "CMD.exe";
                            string cmdToBeExecuted = " azcopy.exe" + "  \"" + folderLocation + "\"  " + " \"" + blobEndPoint + cmbBlobDir.SelectedItem.ToString().Substring(1) + txtDirName.Text + "\"  " + cmbFileSelection.SelectedItem.ToString() + " /destKey:" + accountKey + "   /v  /Y  >dest.log";
                            azcopyProcessStartInfo.Arguments = "/c " + cmdToBeExecuted;
                            azcopyProcessStartInfo.UseShellExecute = false;
                            azcopyProcessStartInfo.CreateNoWindow = true;
                            azcopyProcessStartInfo.RedirectStandardError = true;
                            cmd.StartInfo = azcopyProcessStartInfo;
                            cmd.Start();
                            if (!cmd.StandardError.ReadToEnd().Equals(string.Empty))
                            {
                                MessageBox.Show("The following Error occurred :" + cmd.StandardError.ReadToEnd());
                            }
                            cmd.WaitForExit();

                            /*validation section*/

                            int output = validateCompletedRequest();
                            if (output == 0)
                            {
                                this.DialogResult = DialogResult.None;
                            }
                            else if (output == 1)
                            {
                                this.Close();
                            }
                            else if (output == 2)
                            {
                                this.DialogResult = DialogResult.Cancel;
                                this.Close();
                            }      
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        this.DialogResult = DialogResult.None;
                    }
                }                       

            }
        }

        private int validateCompletedRequest()
        {
            if (!File.Exists("dest.log"))
            {
                MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                //this.DialogResult = DialogResult.None;
                return 0;
            }
            else
            {
                linesDestLog = File.ReadAllLines("dest.log");
                foreach (var line in linesDestLog)
                {
                    if (line.Contains("Total files transferred"))
                    {
                        totalFilesTransfered = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer successfully"))
                    {
                        filesTranferedSuccessfully = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                    else if (line.Contains("Transfer failed"))
                    {
                        filesFailed = ((line.Substring(line.IndexOf(":") + 1)).Trim());
                    }
                }

                if (totalFilesTransfered == string.Empty || filesTranferedSuccessfully == string.Empty)
                {
                    MessageBox.Show("The status of the Last operation cannot be determined as the Log file failed to generate in the application directory");
                    //this.DialogResult = DialogResult.None;
                    return 0;
                }

                if (totalFilesTransfered.Equals(filesTranferedSuccessfully))
                {
                    DialogResult result = MessageBox.Show("All Files Transfered Successfully!!, You want to transfer another set of files?", "Question", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //this.DialogResult = DialogResult.None;
                        return 0;
                    }
                    else
                    {
                        //this.Close();
                        return 1;
                    }
                }
                else if (filesTranferedSuccessfully == "0")
                {
                    MessageBox.Show("The Operation Failed, Kindly refer to the Dest.log in the Application directory for more details");
                    
                    //this.DialogResult = DialogResult.Cancel;
                    //this.Close();
                    return 2;
                }
                else
                {
                    MessageBox.Show("Sone of the Files did not upload successfully, Please refer to the dest.log in the Application directory for details");
                    //this.Close();
                    return 1;
                }
            } 
        }

        public static bool IsAlphaNum(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;

            return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnResetFields_Click(object sender, EventArgs e)
        {
            folderLocation = "";
            radYes.Checked = true;
            radNo.Checked = false;
            cmbFileSelection.Enabled = false;
            cmbFileSelection.Text = "";
            cmbBlobDir.Text = "";
            radCreateDir.Checked = false;
            radCreateDir.Enabled = false;
            radNotCreateDir.Checked = true;
            radNotCreateDir.Enabled = false;
            txtDirName.Text = "";
            txtDirName.Enabled = false;
            lblCreareNewDirectoryonBlob.Enabled = false;
            lblDirectoryName.Enabled = false;

        }

        private void cmbFileSelection_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) { return; }
            string text = cmbFileSelection.GetItemText(cmbFileSelection.Items[e.Index]);
            e.DrawBackground();
            using (SolidBrush br = new SolidBrush(e.ForeColor))
            { e.Graphics.DrawString(text, e.Font, br, e.Bounds); }
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            { toolTip1.Show(text, cmbFileSelection, e.Bounds.Right, e.Bounds.Bottom); }
            e.DrawFocusRectangle();
        }

        private void cmbFileSelection_DropDownClosed(object sender, EventArgs e)
        {
            toolTip1.Hide(cmbFileSelection);
        }

        private void cmbFileSelection_Leave(object sender, EventArgs e)
        {
            toolTip1.Hide(cmbFileSelection);
        }      
    }
}
